import io
import os
import traceback
import zipfile
from abc import ABC

from PIL import Image


def img_to_format_jpg(buf, dstFile):
    """
    vip 图片标准程序
    :param buf:
    :param dstFile:
    :return:
    """
    exMsg = ''
    try:
        srcImg = Image.open(io.BytesIO(buf))
        dstImg = srcImg.resize((108, 150), Image.ANTIALIAS).convert('RGB')
        dstImg.save(dstFile, 'JPEG')
    except:
        exMsg = '* %s' % traceback.format_exc()
        print(exMsg)
    if exMsg:
        return False

    return True


class ZIPFileUtils(object):

    @classmethod
    def get_zip_file(cls, filePath):
        """
        获取zip文件对象
        :param filePath:
        :return:
        """
        assert filePath.split(os.extsep)[-1] == "zip"
        return zipfile.ZipFile(filePath)

    @classmethod
    def get_name_list(cls, zipobj: zipfile.ZipFile):
        return zipobj.namelist()

    @classmethod
    def get_file_name(cls, zipobj: zipfile.ZipFile):
        return zipobj.filename


class FileToSql(ABC):

    def __init__(self):
        self.filePath = ""
        self.keys = []
        self.keydicts = {}
        self.datadicts = {}

    def set_filePath(self, filePath):
        self.filePath = filePath
        return self

    def get_file_num(self):
        pass

    def get_one_ext_file(self, dirPath, extname):
        for path, dirNames, fileNames in os.walk(dirPath, topdown=True):
            # 获取当前目录的所有文件
            for fileName in fileNames:
                filePath = os.path.join(path, fileName)
                if fileName.split(os.extsep)[-1] == extname:
                    yield filePath

    def get_keys(self):
        return self.keys


if __name__ == "__main__":
    dicts = {}
    with open("./temp4.txt", "r", encoding="utf-8") as f:
        for line in f:
            line_list = line.replace("\n", "").split("\t")
            dicts[line_list[0]] = line_list[1]
    filetosql = FileToSql()
    filePathBool = True
    txtPathBool = True
    count = 0
    with open("./id.txt", "w", encoding="utf-8") as f:
        # r"E:\down_data\FTP\jss_zl\20181012\专利元数据\2018"
        msg = ""
        for filePath in filetosql.get_one_ext_file(r"E:\down_data\FTP\jss_zl\20181012\专利元数据\2018",
                                                   "zip"):
            print(filePath)

            zipobj = ZIPFileUtils.get_zip_file(filePath)
            namelist = ZIPFileUtils.get_name_list(zipobj)
            for file in namelist:
                extname = file.split(os.extsep)[-1]
                if extname == "gif" or extname == "jpg":
                    count += 1
                    filename = os.path.split(file)[-1]
                    filename = os.extsep.join(filename.split(os.extsep)[:-1])
                    filename = filename.replace("CN", "").replace(".", "").replace("ABS", "")
                    pub_no = dicts[filename]
                    if not pub_no:
                        continue
                    dstDir = os.path.join(r"E:\down_data\cnipapatent\cnipapatent_cover_20181030", pub_no[:3].lower(),
                                          pub_no[3:7].lower())
                    if not os.path.exists(dstDir):
                        os.makedirs(dstDir)
                    dstFile = os.path.join(dstDir, pub_no.lower() + ".jpg")
                    if count % 100 == 1:
                        print(count)
                    bytes = zipobj.read(file)
                    img_to_format_jpg(bytes, dstFile)

        print("Total %d" % count)
